<template>
    <div class="login-container">
      <div class="loading" v-if="loading">
        <div class="spinner"></div>
        <p>正在获取用户信息...</p>
      </div>
      <div class="error" v-if="errorMsg">
        <i class="icon-error"></i>
        <p>{{ errorMsg }}</p>
      </div>
    </div>
  </template>
  
  <script>
  import { getWechatUserInfo, wechatLogin } from '@/api/wechat';
  import { getQueryParam } from '@/utils/url';
  import { getToken, setToken, removeToken } from '@/utils/auth'
  import { getUserProfile } from '@/api/system/user'
  import { getInUsing } from '@/api/business/record'
  import { listDevice,getDevice } from '@/api/device/device'
  import { getIot } from "@/api/device/iot"
  
  export default {
    name: 'WechatLogin',
    data() {
      return {
        loading: true,
        errorMsg: ''
      };
    },
    mounted() {
      this.initLogin();
    },
    methods: {
      async initLogin() {
        try {
          
          const code = getQueryParam('code');
          if (!code) {
            this.redirectToWechatAuth();
            return;
          }

          const { data: userInfo } = await getWechatUserInfo(code);
          if (!userInfo || !userInfo.openId) {
            throw new Error('获取用户信息失败');
          }

          const loginResult = await wechatLogin(userInfo);
          if (loginResult && loginResult.code === 200) {
            setToken(loginResult.token);
            getUserProfile().then(res => {
                window.userInfo = res.data
            })
            // 若检测到用户正在用电，跳转到 /wechat/inUsing
            getInUsing().then(res => {
                window.record = res.data
                if (window.record) {
                  window.orderId = window.record.orderId
                  /** 
                  const query = {
                    meterNo: window.meterNo
                  }
                  listDevice(query).then(response => {
                    window.deviceInfo = response.rows[0]
                    window.meterNo = window.deviceInfo.meterNo
                    window.meterId = window.deviceInfo.id
                    getIot(window.deviceInfo.iotModuleId).then(res => {
                      window.iotModule = res.data
                      window.imei = window.iotModule.imei
                      this.$router.push('/wechat/inUsing');
                    })
                  })
                  */
                  getDevice(window.record.meterId).then(res => {
                    window.deviceInfo = res.data
                    window.meterNo = window.deviceInfo.meterNo
                    window.meterId = window.deviceInfo.id
                    getIot(window.deviceInfo.iotModuleId).then(res => {
                      window.iotModule = res.data
                      window.imei = window.iotModule.imei
                      this.$router.push('/wechat/inUsing');
                    })
                  })
                  this.$message.success('您有正在进行的用电记录，正在跳转页面继续使用');
                  
                } else {
                  this.$router.push('/wechat/index');
                }
            })
          } else {
            throw new Error(loginResult.msg || '登录失败');
          }
        } catch (error) {
          console.error('登录失败', error);
          // 授权码相关错误的特殊处理
          if (error.message && (error.message.includes('授权码已失效') || error.message.includes('授权码已被使用'))) {
            this.$router.push('/wechat/index');
          } else {
            this.errorMsg = error.message || '登录过程出错，请重试';
          }
        } finally {
          this.loading = false;
        }
      },
      
      // 跳转到微信授权页面
      redirectToWechatAuth() {
        const appId = process.env.VUE_APP_WECHAT_APPID || 'wxbff98f0816c4c35c';
        const redirectUri = encodeURIComponent(window.location.href);
        const scope = 'snsapi_userinfo'; // 静默授权使用snsapi_base，需要用户信息用snsapi_userinfo
        const state = 'STATE';
        
        const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
        
        window.location.href = authUrl;
      }
    }
  };
  </script>
  
  <style scoped>
  .login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background-color: #f5f5f5;
  }
  
  .loading {
    text-align: center;
  }
  
  .spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto;
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #07c160;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .error {
    color: #f53f3f;
    text-align: center;
    padding: 20px;
  }
  
  .icon-error {
    font-size: 24px;
    margin-bottom: 8px;
  }
  
  @keyframes spin {
    to { transform: rotate(360deg); }
  }
  </style>
  